/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("yjy_whole_cost",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Entity.DomainModels;
using VOL.Finance.IServices;
using sysio = System.IO;
using sysnet = System.Net;
using VOL.Core.DBManager;
using System.Linq;
using OfficeOpenXml.Style;
using OfficeOpenXml;
using System.IO;
using VOL.Core.Extensions;
using VOL.Core.Utilities;
using Microsoft.AspNetCore.Authorization;
using VOL.Core.Filters;
using System.Collections;
using Newtonsoft.Json;
using System.Net;
using Microsoft.OpenApi.Writers;
using Microsoft.VisualBasic;
using VOL.Core.Infrastructure;

namespace VOL.Finance.Controllers
{
    public partial class yjy_whole_costController
    {
        private readonly Iyjy_whole_costService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;

        [ActivatorUtilitiesConstructor]
        public yjy_whole_costController(
            Iyjy_whole_costService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }
        [ApiActionPermission()]//权限重写，在控制器中增加
        [HttpPost, Route("GetPageData"), AllowAnonymous]
        public override ActionResult GetPageData([FromBody] PageDataOptions loadData)
        {
            return base.GetPageData(loadData);
        }
        
        /// <summary>
        /// 模板下载方法
        /// </summary>
        /// <param name="car_type"></param>
        /// <returns></returns>
        [ApiActionPermission()]//权限重写，在控制器中增加
        [HttpGet, Route("DownLoadTemplate1"), AllowAnonymous]
        public ActionResult DownLoadTemplate1(string car_type,string yjy_whole_info_id)
        {
            WebResponseContent webResponse = new WebResponseContent();
            if (string.IsNullOrEmpty(car_type)&&string.IsNullOrEmpty(yjy_whole_info_id))
            {
                return Json(webResponse.Error("参数不能为空，请重新操作！"));
            }
            string sql = "SELECT a.* FROM yjy_whole_cost_template a JOIN (SELECT ywct.unique_value,MAX(ywct.level) AS LEVEL FROM yjy_whole_cost_template ywct GROUP BY ywct.unique_value) b ON a.unique_value = b.unique_value AND a.level = b.level where type = @type ORDER BY a.serial_number ASC ";
            List<yjy_whole_cost_template> list = DBServerProvider.SqlDapper.QueryList<yjy_whole_cost_template>(sql,new { type = car_type}).ToList();
            string sql2 = " SELECT * FROM  yjy_whole_cost_template a WHERE TYPE = @type ORDER BY a.serial_number ASC , a.[level] ASC  ";
            List<yjy_whole_cost_template> list2 = DBServerProvider.SqlDapper.QueryList<yjy_whole_cost_template>(sql2, new {type = car_type}).ToList();
            yjy_whole_info info = DBServerProvider.DbContext.Set<yjy_whole_info>().Where(x => x.yjy_whole_info_id == Guid.Parse(yjy_whole_info_id)).FirstOrDefault(); 
            string fileName = "整车成本数据表.xlsx";
            string fullFileName = exportWholeCost(info,list,list2,fileName);
            return File(sysio.File.ReadAllBytes(fullFileName), sysnet.Mime.MediaTypeNames.Application.Octet, fileName);
        }
      
        /// <summary>
        /// 模板下载 ：整车数据写入
        /// </summary>
        /// <param name="list"></param>
        /// <param name="list2"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private string exportWholeCost(yjy_whole_info info,List<yjy_whole_cost_template> list, List<yjy_whole_cost_template> list2, string fileName)
        {
            string path = null;
            path = path ?? $"Download/ExcelExport/{DateTime.Now.ToString("yyyyyMMdd")}/";
            string fullPath = path.MapPath();
            fileName = Guid.NewGuid() + "_" + fileName;
            if (!Directory.Exists(fullPath)) Directory.CreateDirectory(fullPath);
            ExcelPackage excel = new ExcelPackage();
            ExcelWorksheet sheet = excel.Workbook.Worksheets.Add("sheet1");
            sheet.Cells.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
            sheet.Cells.Style.Border.Left.Style = ExcelBorderStyle.Thin;
            sheet.Cells.Style.Border.Right.Style = ExcelBorderStyle.Thin;
            sheet.Cells.Style.Border.Top.Style = ExcelBorderStyle.Thin;
            sheet.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
            sheet.Cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;

            sheet.Cells["A1"].Value = "公司类型";
            sheet.Cells["B1"].Value = "车辆类型";
            sheet.Cells["C1"].Value = "整车物料号";
            sheet.Cells["D1"].Value = "整车车型型号";
            sheet.Cells["E1"].Value = "模板层级对应唯一值";
            sheet.Cells["F1"].Value = "层级关系描述";
            sheet.Cells["G1"].Value = "描述";
            sheet.Cells["H1"].Value = "一级物料号";
            sheet.Cells["I1"].Value = "一级物料号名称";
            sheet.Cells["J1"].Value = "金额";

            if (!list.IsNullOrEmpty() && list.Count > 0)
            {
                for (int i = 0; i < list.Count(); i++)
                {
                    int j = 0;
                    int rowIndex = i +2;
                    int columnIndex = j + 1;
                    if (info!=null)
                    {
                        int index = (int)info.type - 1;
                        int index_car = (int)info.car_type - 1;
                        sheet.Cells[rowIndex, columnIndex].Value = DictionaryManager.GetDictionary("整车成本公司类型").Sys_DictionaryList[index].DicName;
                        sheet.Cells[rowIndex, columnIndex+1].Value = DictionaryManager.GetDictionary("整车成本车辆类型").Sys_DictionaryList[index_car].DicName;
                        sheet.Cells[rowIndex, columnIndex + 2].Value = info.materialnum;
                        sheet.Cells[rowIndex, columnIndex + 3].Value = info.materialnum_name;
                    }
                    
                    sheet.Cells[rowIndex, columnIndex + 4].Value = list[i].unique_value;
                    string remark = "";
                    int level = 1;
                    foreach (var item in list2)
                    {
                        if (item.unique_value.Equals(list[i].unique_value) && item.level == level && level <= item.level)
                        {
                            remark += item.describe + "-";
                            level++;
                        }

                    }
                    sheet.Cells[rowIndex, columnIndex + 5].Value = remark.Substring(0,remark.Length-1);
                }
            }
            FileInfo file = new FileInfo(fullPath + fileName);
            excel.SaveAs(file);
            return fullPath + fileName;
        }
        
        /// <summary>
        /// 查看数据汇总
        /// </summary>
        /// <param name="yjy_whole_info_id">整车基本信息id</param>
        /// <returns></returns>
        [ApiActionPermission()]//权限重写，在控制器中增加
        [HttpPost, Route("getWholeCostListSummary"), AllowAnonymous]
        public List<whole_cost_vo> getWholeCostListSummary(string yjy_whole_info_id)
        {
            WebResponseContent webResponse = new WebResponseContent();
            string sql = "SELECT * FROM yjy_whole_cost ywc WHERE yjy_whole_info_id = @yjy_whole_info_id";
            List<yjy_whole_cost> list = DBServerProvider.SqlDapper.QueryList<yjy_whole_cost>(sql, new { yjy_whole_info_id = yjy_whole_info_id }).ToList();
            List<whole_cost_vo> listVo = new List<whole_cost_vo>();
            if (list.Count==0)
            {
                return listVo;
            }
            foreach (var item in list)
            {
                whole_cost_vo vo = new whole_cost_vo();
                vo.yjy_whole_cost_id = item.yjy_whole_cost_id;
                vo.type = item.type;
                vo.car_type = item.car_type;
                vo.materialnum = item.materialnum;
                vo.materialnum_name = item.materialnum_name;
                vo.unique_value = item.unique_value;
                vo.hierarchy_describe = item.hierarchy_describe;
                vo.describe = item.describe;
                vo.componentnum = item.componentnum;
                vo.componentnum_name = item.componentnum_name;
                vo.amount = item.amount;
                vo.yjy_whole_info_id = item.yjy_whole_info_id;
                vo.level_state_1 = 0;
                vo.level_state_2 = 0;
                vo.level_state_3 = 0;
                vo.level_state_4 = 0;
                string describe = item.hierarchy_describe;
                string[] words = describe .Split('-');
                for (int i = 0; i<words.Length ; i++)
                {
                    if (i==0)
                    {
                        vo.level_name_1 = words[i];
                    }else if (i==1)
                    {
                        vo.level_name_2 = words[i];
                    }else if (i==2)
                    {
                        vo.level_name_3 = words[i];
                    }else if (i == 3)
                    {
                        vo.level_name_4 = words[i];
                    }
                    
                }
                listVo.Add( vo );   
            }
            whole_cost_vo cost_vo = listVo[0];
            string level_name1 = cost_vo.level_name_1;
            string level_name2 = cost_vo.level_name_2;
            string level_name3 = cost_vo.level_name_3;
            string level_name4 = cost_vo.level_name_4;
            for (int j = 0;j < listVo.Count; j++)
            {
                whole_cost_vo item = listVo[j];
                if (j==0)
                {
                    item.level_state_1 = 1;
                    item.level_state_2 = 1;
                    item.level_state_3 = 1;
                    item.level_state_4 = 1;
                }
                if (level_name1 != item.level_name_1)
                {
                    level_name1 = item.level_name_1;
                    item.level_state_1 = 1;
                }
                if (level_name2 != item.level_name_2)
                {
                    level_name2 = item.level_name_2;
                    item.level_state_2 = 1;
                }
                if (level_name3 != item.level_name_3)
                {
                    level_name3 = item.level_name_3;
                    item.level_state_3 = 1;
                }
                if (level_name4 != item.level_name_4)
                {
                    level_name4 = item.level_name_4;
                    item.level_state_4 = 1;
                }
                int count1 = listVo.Where(a => a.level_name_1 == item.level_name_1).Count();
                item.level_count_1 = count1;
                int count2 = listVo.Where(a => a.level_name_2 == item.level_name_2).Count();
                item.level_count_2 = count2;
                int count3 = listVo.Where(a => a.level_name_3 == item.level_name_3).Count();
                item.level_count_3 = count3;
                int count4 = listVo.Where(a => a.level_name_4 == item.level_name_4).Count();
                item.level_count_4 = count4;

            }
            return listVo;
        }
        
        /// <summary>
        /// 导出整车数据汇总表 
        /// </summary>
        /// <param name="yjy_whole_info_id"></param>
        /// <returns></returns>
        [ApiActionPermission()]//权限重写，在控制器中增加
        [HttpPost, Route("exportWholeCostSummary"), AllowAnonymous]
        public ActionResult exportWholeCostSummary(string yjy_whole_info_id)
        {
            string fileName = "整车数据汇总表.xlsx";
            List<whole_cost_vo> list = new List<whole_cost_vo>();
            list = getWholeCostListSummary(yjy_whole_info_id);
            string fullFileName = exportWholeCostSummaryExcel(list, fileName);
            return File(sysio.File.ReadAllBytes(fullFileName), sysnet.Mime.MediaTypeNames.Application.Octet, fileName);
        }
        
        /// <summary>
        /// 导出整车数据汇总表
        /// </summary>
        /// <param name="list"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private string exportWholeCostSummaryExcel(List<whole_cost_vo> list, string fileName)
        {
            string path = null;
            path = path ?? $"Download/ExcelExport/{DateTime.Now.ToString("yyyyyMMdd")}/";
            string fullPath = path.MapPath();
            fileName = Guid.NewGuid() + "_" + fileName;
            if (!Directory.Exists(fullPath)) Directory.CreateDirectory(fullPath);
            ExcelPackage excel = new ExcelPackage();
            ExcelWorksheet sheet = excel.Workbook.Worksheets.Add("sheet1");
            sheet.Cells.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
            sheet.Cells.Style.Border.Left.Style = ExcelBorderStyle.Thin;
            sheet.Cells.Style.Border.Right.Style = ExcelBorderStyle.Thin;
            sheet.Cells.Style.Border.Top.Style = ExcelBorderStyle.Thin;
            sheet.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
            sheet.Cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            whole_cost_vo vo = list[0];
            sheet.Cells["A1:D1"].Value = "边际测算";
            sheet.Cells["A1:D1"].Merge = true;
            sheet.Cells["E1"].Value = vo.materialnum_name; //物料号名称
            sheet.Cells["F1"].Value = "备注";
            sheet.Cells["G1"].Value = "汇总金额";
            sheet.Cells["A2:D2"].Value = "物料号";
            sheet.Cells["A2:D2"].Merge = true;
            sheet.Cells["E2"].Value = vo.materialnum; //物料号
            sheet.Cells["F2"].Value = "   ";
            sheet.Cells["G2"].Value = "   ";

            if (!list.IsNullOrEmpty() && list.Count > 0)
            {
                int indexstart = 0;
                int indexend = 0;
                int indexstart2 = 0;
                int indexend2 = 0;
                int indexstart3 = 0;
                int indexend3 = 0;
                for (int i = 0; i < list.Count(); i++)
                {
                    int j = 0;
                    int rowIndex = i + 3;
                    int columnIndex = j + 1;
                    if (list[i].level_state_1==1)
                    {
                        indexstart = rowIndex;
                        indexend = list[i].level_count_1 + indexstart-1;
                        sheet.Cells["A"+ indexstart + ":A"+ indexend].Merge = true;
                    }
                    sheet.Cells[rowIndex, columnIndex].Value = list[i].level_name_1;

                    if (list[i].level_state_2 == 1)
                    {
                        indexstart2 = rowIndex;
                        indexend2 = list[i].level_count_2 + indexstart2 - 1;
                        sheet.Cells["B" + indexstart2 + ":B" + indexend2].Merge = true;
                    }
                    sheet.Cells[rowIndex, columnIndex+1].Value = list[i].level_name_2;
                    sheet.Cells[rowIndex, columnIndex+2].Value = list[i].level_name_3;
                    sheet.Cells[rowIndex, columnIndex+3].Value = list[i].describe;
                    sheet.Cells[rowIndex, columnIndex+4].Value = list[i].componentnum;
                    sheet.Cells[rowIndex, columnIndex+5].Value = list[i].componentnum_name;
                    sheet.Cells[rowIndex, columnIndex+6].Value = list[i].amount;
                }
            }
            FileInfo file = new FileInfo(fullPath + fileName);
            excel.SaveAs(file);
            return fullPath + fileName;
        }
        
        /// <summary>
        /// 生成数据汇总
        /// </summary>
        /// <param name="yjy_whole_info_id">整车基本信息id</param>
        /// <param name="materialnum">整车头物料号</param>
        /// <returns></returns>
        [ApiActionPermission()]//权限重写，在控制器中增加
        [HttpPost, Route("createWholeCostSummary"), AllowAnonymous]
        public ActionResult createWholeCostSummary(string yjy_whole_info_id,string materialnum)
        {

            WebResponseContent webResponse = new WebResponseContent();
            decimal totalAmout = 0;
            //查找一级组件 treeid=1
            List<yjy_whole_wlzb> listWlzb = DBServerProvider.DbContext.Set<yjy_whole_wlzb>().Where(x => x.materialnum == materialnum && x.tree_id == 1).ToList();
            if (listWlzb.Count==0)
            {
                return Json(webResponse.Error("该整车还没有物料数据"));
            }
            foreach (var item in listWlzb)
            {
                yjy_whole_cost yjy_Whole_Cost = DBServerProvider.DbContext.Set<yjy_whole_cost>().Where(x => x.componentnum == item.componentnum && x.materialnum == materialnum).ToList().FirstOrDefault();
                if (yjy_Whole_Cost!=null)
                {
                    List<yjy_whole_wlzb> listWlzbChild = DBServerProvider.DbContext.Set<yjy_whole_wlzb>().Where(x => x.parent_componentnum == item.componentnum && x.materialnum == materialnum).ToList();
                    foreach (var item1 in listWlzbChild)
                    {
                        if (item1.finalprice.IsNullOrEmpty())
                        {
                            totalAmout = totalAmout + (decimal)(item1.finalprice * item1.num);
                        }
                        else
                        {
                            totalAmout = totalAmout + (decimal)(item1.unitprice * item1.num);
                        }    
                    }
                    yjy_Whole_Cost.amount = totalAmout;
                    DBServerProvider.DbContext.Update(yjy_Whole_Cost);
                }   
            }
            DBServerProvider.DbContext.SaveChanges();
            return Json(webResponse.OK("数据生成成功！"));
        }

        /// <summary>
        /// 导入方法
        /// </summary>
        /// <param name="fileInput"></param>
        /// <param name="yjy_whole_info_id"></param>
        /// <returns></returns>
        [ApiActionPermission()]//权限重写，在控制器中增加
        [HttpPost, Route("Import1")]
        public ActionResult Import1(List<IFormFile> fileInput, string yjy_whole_info_id)
        {
            WebResponseContent webResponse = new WebResponseContent();
            if (fileInput == null || fileInput.Count == 0)
            {
                return Json(webResponse.Error("请选择文件！"));
            }
            if (string.IsNullOrEmpty(yjy_whole_info_id))
            {
                return Json(webResponse.Error("参数丢失，请重新上传！"));
            }
            yjy_whole_info info = DBServerProvider.DbContext.Set<yjy_whole_info>().Where(x => x.yjy_whole_info_id == Guid.Parse(yjy_whole_info_id)).FirstOrDefault();
            string materialnum = info.materialnum;
            List<yjy_whole_cost> list = DBServerProvider.DbContext.Set<yjy_whole_cost>().Where(x => x.materialnum == materialnum).ToList();
            if (list.Count > 0)
            {
                return Json(webResponse.Error("该整车成本数据已经上传，不用重复操作！"));
            }
            return Json(_service.Yjy_Whole_Cost_Import(fileInput, yjy_whole_info_id));
        }
    }
}